//
//  KKImageBrowserViewController.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/29.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKImageBrowserViewController.h"

#import "KKImageBrowser.h"

typedef void(^KKImageBrowserItemCellEventBlockHandle)(void);

@interface KKImageBrowserItemCell : UICollectionViewCell<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, assign) CGFloat initScale;    /**<初始的缩放倍数*/

@property (nonatomic, strong) KKImageBrowserItem *item;

@property (nonatomic, strong) KKImageBrowserItemCellEventBlockHandle eventBlockHandle;

@end

@implementation KKImageBrowserItemCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        self.backgroundColor = [UIColor blackColor];
        
        _scrollView = [[UIScrollView alloc] initWithFrame: self.bounds];
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _scrollView.delegate = self;
        _scrollView.minimumZoomScale = 1.0;
        _scrollView.backgroundColor = [UIColor clearColor];
        [self addSubview: _scrollView];
        
        _imageView = [[UIImageView alloc] init];
        _imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
        _imageView.userInteractionEnabled = YES;
        [_imageView addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(on_Tap:)]];
        [_scrollView addSubview: _imageView];
        
    }
    return self;
}

- (void)on_Tap:(UITapGestureRecognizer*)tapper {
    
    if (_scrollView.zoomScale > _initScale) {
        [_scrollView setZoomScale: _initScale animated: YES];
    }
    else {
        //  关闭图片显示
        if (self.eventBlockHandle) {
            self.eventBlockHandle();
        }
    }
}

- (void)setItem:(KKImageBrowserItem *)item {
    if (_item != item) {
        _item = item;
        
        if (_item.itemImage == nil) {
            //  如果资源图片不为空，则用链接去获取图片数据
            NSString *imagePath = _item.itemPath;
            if ([imagePath hasPrefix: @"http"]) {
                NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString: imagePath]];
                __weak typeof(self) weakSelf = self;
                [_imageView setImageWithURLRequest: request placeholderImage: nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
                    weakSelf.imageView.image = image;
                    [weakSelf private_updateSubViewBounds];
                } failure: nil];
            }
        }
        else {
            _imageView.image = _item.itemImage;
            [self private_updateSubViewBounds];
        }
    }
}

- (void)private_updateSubViewBounds {
    
    CGFloat scrollViewWidth = CGRectGetWidth(_scrollView.bounds);
    CGFloat scrollViewHeight = CGRectGetHeight(_scrollView.bounds);
    UIImage *image = _imageView.image;
    {
        if (image.size.width > scrollViewWidth) {
            // 如果图片过大
            CGFloat scale = image.size.width / scrollViewWidth;
            CGFloat showImageHeight = image.size.height / scale;
            CGFloat origin_y = showImageHeight > scrollViewHeight ? 0.0 : fabs(scrollViewHeight - showImageHeight)/2.0;
            self.imageView.frame = CGRectMake(0, origin_y, scrollViewWidth, showImageHeight);
            
            [_scrollView setMaximumZoomScale: scale];
            [_scrollView setMinimumZoomScale: 1.0];
            [_scrollView setZoomScale: 1.0];
            _initScale = 1.0;
        }
        else {
            CGFloat origin_x = fabs(scrollViewWidth - image.size.width)/2.0;
            CGFloat scale = image.size.width / (scrollViewWidth - origin_x *2);
            CGFloat showImageHeight = image.size.height / scale;
            CGFloat origin_y = showImageHeight > scrollViewHeight ? 0.0 : fabs(scrollViewHeight - showImageHeight)/2.0;
            
            self.imageView.frame = CGRectMake(origin_x, origin_y, image.size.width, showImageHeight);
            [_scrollView setMinimumZoomScale:scale];
            [_scrollView setMaximumZoomScale: 2];
            [_scrollView setZoomScale:scale];
            _initScale = scale;
        }
    }
}

#pragma mark - UIScrollViewDelegate methods

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    _imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
}


@end


#pragma mark -
#pragma mark - KKImageBrowserViewController Class
@interface KKImageBrowserViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *itemCollectionView;

@end

@implementation KKImageBrowserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"图片";
    
    self.automaticallyAdjustsScrollViewInsets = false;
    
    CGFloat pointY = 64.0;
    CGFloat heihgt = SCREEN_HEIGHT - pointY;
    
    if (@available(iOS 11.0, *)){
        UIWindow *window = [[UIApplication sharedApplication] delegate].window;
        if (window.safeAreaInsets.top > 0) {
            pointY = 88;
            heihgt = SCREEN_HEIGHT - pointY - window.safeAreaInsets.bottom;
        }
    }
    
    //    navigation_item_back
    [self setLeftBarButtonItemWithImageName: @"navigation_item_back" style: UIBarButtonItemStylePlain target: self action: @selector(action_back:)];
    
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    
    self.itemCollectionView = [[UICollectionView alloc] initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout: flowLayout];
    self.itemCollectionView.backgroundColor = [UIColor redColor];
    self.itemCollectionView.dataSource = self;
    self.itemCollectionView.delegate = self;
    self.itemCollectionView.pagingEnabled = true;
    [self.view addSubview: self.itemCollectionView];
    
    [self.itemCollectionView addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(on_Tap:)]];
    
    if (@available(iOS 11.0, *)){
        self.itemCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self.itemCollectionView registerClass: [KKImageBrowserItemCell class] forCellWithReuseIdentifier: @"KKImageBrowserItemCell"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
}

#pragma mark - Action methods
- (void)action_back:(id)sender {
    [self.navigationController dismissViewControllerAnimated: true completion: nil];
}

- (void)on_Tap:(UITapGestureRecognizer*)tapper {
    if (self.navigationController.isNavigationBarHidden) {
        [self.navigationController setNavigationBarHidden: false animated: true];
    }
    else {
        [self.navigationController setNavigationBarHidden: true animated: true];
    }
}

#pragma mark -

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.arr_items.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    KKImageBrowserItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"KKImageBrowserItemCell" forIndexPath: indexPath];
    KKImageBrowserItem *item = [self.arr_items objectAtIndex: indexPath.row];
    [cell setItem: item];
    
    __weak typeof(self) weakSelf = self;
    cell.eventBlockHandle = ^{
        if (weakSelf.navigationController.isNavigationBarHidden) {
            [weakSelf.navigationController setNavigationBarHidden: false animated: true];
        }
        else {
            [weakSelf.navigationController setNavigationBarHidden: true animated: true];
        }
    };
    return cell;
}

@end
